package com.sunshine.ssm.system;

import com.sunshine.ssm.entity.vo.Email;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * @Description:
 * @FileName: com.sunshine.ssm.service.
 * @author: Hong.Wei
 * @Date: 2016/12/23 15:27
 */
@Service
public class EmailService implements IEmailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmailService.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void sendMail(Email email) {
        sendMailByAsynchronousMode(email);
//        MimeMessage msg = mailSender.createMimeMessage();
//        MimeMessageHelper msgHelper = new MimeMessageHelper(msg, "UTF-8");
//        msgHelper.setFrom(email.getFrom(), email.getUsername());
//        msgHelper.setTo(email.getTo());
//        msgHelper.setSubject(email.getSubject());
//        msgHelper.setText(email.getDetails(), true);  // true表示设定html格式
//        mailSender.send(msg);
    }

    @Override
    public void sendMailByAsynchronousMode(final Email email) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    sendMailBySynchronizationMode(email);
                } catch (Exception e) {
                    LOGGER.error("邮件发送失败！", e);
                }
            }
        });
    }

    @Override
    public void sendMailBySynchronizationMode(Email email) throws Exception {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper msgHelper = new MimeMessageHelper(msg, "UTF-8");
        msgHelper.setFrom(email.getFrom(), email.getUsername());
        msgHelper.setTo(email.getTo());
        msgHelper.setSubject(email.getSubject());
        msgHelper.setText(email.getDetails(), true);  // true表示设定html格式
        mailSender.send(msg);
    }

}
